package person.twj.jwt.controller;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import person.twj.jwt.core.security.constant.TokenConstants;
import person.twj.jwt.core.security.util.TokenUtil;
import person.twj.jwt.core.security.util.UserToken;
import person.twj.jwt.domain.vo.RsVo;

import java.io.IOException;
import java.util.Map;

@Controller
@Slf4j
//@RequestMapping("/authentication")
public class AuthenticationController {


    /**
     * 通过refresh_token，获取新的token
     * @return
     */
    @PostMapping("/refreshToken")
    public void refreshToken(@RequestBody Map<String,Object> param, HttpServletResponse response) throws IOException {

        // 1. 验证 refreshToken是否过时
        // 2. 生成 token
        // 3. 返回 token

        // 解析并验证token

        String refreshToken = (String)param.get("refreshToken");
        if(refreshToken!=null){
            try {
                UserToken userToken = TokenUtil.parseTokenInfo(refreshToken);
                RsVo.success("刷新token成功", map -> {
                            map.put("access_token", TokenUtil.createToken(userToken));//有效期2个小时
                            map.put("expires_in", TokenConstants.EXPIRES_IN);
                        })
                        .writeTo(response);
            }catch (BadCredentialsException e){
                RsVo.failed(1,"刷新token失败，令牌不正确").writeTo(response);
            }catch (CredentialsExpiredException cee){
                RsVo.failed(3,"刷新token失败，令牌已过期").writeTo(response);
            }catch (Exception e){
                log.debug("刷新token失败，未知错误 ",e);
                RsVo.failed(-1,"刷新token失败，未知错误").writeTo(response);
            }
        }else{
            RsVo.failed(2,"刷新token失败，缺少参数 refreshToken ").writeTo(response);

        }




    }

//    @RequestMapping("/login/process")
//    public String process(){
//        System.out.println("访问：/authentication/login");
//        return "/authentication/login";
//    }

}
